
const mongoose = require('mongoose')
const Role = mongoose.model('role')
const RoleVld = require('./role.vld')
const { Resp } = require('../../config/utils')

class RoleCtrl {
  /**
   * @api {get} /roles 获取角色
   * @apiName roles_list
   * @apiGroup roles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "获取角色成功！",
        "data": {
          "list": [],
          "count": 1
        }
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async getRoles(ctx, next) {
    let roles = Role.find({},{__v: 0})
    let [list, count] = await Promise.all([ roles, Role.countDocuments()])
    ctx.body = Resp(1, '获取角色成功！', {list, count})
  }
  /**
   * @api {post} /roles 新增角色
   * @apiName roles_add
   * @apiGroup roles
   * 
   * @apiHeader {String} vf token 
   * 
   * @apiParam {String} name 角色名称
   * @apiParam {String} code 角色代码
   * @apiSuccessExample 返回示例
      HTTP/1.1 200 OK
      {
        "code": 1,
        "msg": "新增角色成功！",
        "data": {}
      }
   * @apiErrorExample 错误示例
      HTTP/1.1 500 Internal Server Error
  */
  async createRoles(ctx, next) {
    let {name, code} = ctx.request.body
    let validate = await RoleVld.createRole(name, code)
    if(validate && validate.status === 0) {
      return ctx.body = Resp(0, validate.msg, null)
    }
    let role = new Role({name, code})
    let result = await role.save()
    return ctx.body = Resp(1, '新增角色成功！', result)
  }
}

module.exports = new RoleCtrl()